import { h } from "koishi"
import { readFile } from "fs/promises"
export const name = "xdi8-data-loader"
export const inject = ["xdi8"]
export async function apply(ctx) {
  ctx.i18n.define("zh", "commands.xdi8", {
    options: {
      version: "显示字表版本",
      reload: "重新加载字表数据",
    },
    messages: {
      reloaded: "已重新加载字表数据。",
    },
  })

  let version = "?"

  async function load() {
    ctx.xdi8.data = JSON.parse(await readFile("node_modules/xdi8-transcriber/lib/data.json", "utf8"))
    try {
      version = (await readFile("node_modules/xdi8-transcriber/README.md", "utf8")).match(/字表已更新至.+/)[0]
    } catch (err) {
      version = "?"
      throw err
    }
  }
  load().catch(ctx.logger.error)

  const patch = function (cmd) {
    if (cmd && cmd.name === "xdi8") try {
      cmd.option("version", "-v")
      cmd.option("reload", "-r", { authority: 3 })
    } catch {}
  }
  patch(ctx.$commander.get("xdi8"))
  ctx.on("command-added", patch)

  ctx.before("command/execute", async argv => {//ctx.logger.debug((o=>(delete o.session,o))({...argv}))
    if (argv.command.name !== "xdi8") return
    if (argv.options.version) return h.text(version)
    if (argv.options.reload) {
      await load()
      return argv.session.i18n(".reloaded")
    }
  })
}
